<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-13 10:15:48
 * @LastEditors: your name
 * @LastEditTime: 2021-05-19 10:32:26
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="1000px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建数据源" : "编辑数据源" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="close"></span>
      </div>
    </div>

    <div class="pl30 pr30">
      <el-row :gutter="40" type="flex">
        <el-col :span="12">
          <el-form :model="formData" ref="form" label-width="120px">
            <el-form-item
              label="数据源Key"
              prop="key"
              :rules="[
                {
                  required: true,
                  message: '数据源Key不能为空',
                  trigger: 'change',
                },
                {
                  pattern: COMMON_CODE_64I_REG.pattern,
                  message: '请输入有效的数据源Key',
                  trigger: 'change',
                },
              ]"
            >
              <template
                slot="label"
              >数据源Key
                <el-tooltip
                  popper-class="custom-popper"
                  :content="COMMON_CODE_64I_REG.message"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-input
                :disabled="!isNew"
                v-model="formData.key"
                placeholder="请输入数据源Key"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item
              label="数据源名称"
              prop="name"
              :rules="[
                {
                  required: true,
                  message: '数据源名称不能为空',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model="formData.name"
                placeholder="请输入数据源名称"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item
              label="数据源类型"
              prop="type"
              :rules="[
                {
                  required: true,
                  message: '请选择数据源类型',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                :disabled="!isNew"
                style="width: 100%"
                v-model="formData.type"
                placeholder="请选择数据源类型"
              >
                <el-option
                  v-for="(value, key) in DATA_SOURCE_TYPE_ENUM"
                  :key="key"
                  :value="key"
                  :label="value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="数据源描述">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="请输入数据源描述"
                :maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="12" style="border-left: 1px solid #dcdfe6">
          <el-tabs v-model="activeTab">
            <el-tab-pane
              v-for="(item, index) in envConfigList"
              :key="index"
              :label="item.name"
              :name="item.key"
            >
              <EnvForm
                :ref="`${item.key}_EnvForm`"
                :type="formData.type"
                :env="item.key"
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="tr">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { DATA_SOURCE_TYPE_ENUM, COMMON_ENV_ENUM } from '@/utils/enum'
import { COMMON_CODE_64I_REG } from '@/utils/reg'

import { postHmdatasource,putHmdatasource } from '@/apis/paas/HmDatasourceController.js'
import { getHmenvironmentList } from '@/apis/paas/HmEnvironmentController.js'
import EnvForm from './EnvForm'

const defaultTab = Object.keys(COMMON_ENV_ENUM)[0]

export default {
  name: 'ReportForm',
  components: {
    EnvForm
  },
  data () {
    return {
      loading: false,
      DATA_SOURCE_TYPE_ENUM,
      COMMON_ENV_ENUM,
      COMMON_CODE_64I_REG,
      showVisible: false,
      envConfigList: [], // 系统显示的环境
      envConfigHiddenList: [], // 隐藏的配置项
      formData: {},
      activeTab: defaultTab,
      callback: () => {}
    }
  },

  computed: {
    isNew () {
      return !this.formData.id
    }
  },

  methods: {
    async open (data = {}, callback) {
      this.envConfigList = await getHmenvironmentList({ hidden: 0 })
      this.showVisible = true
      this.callback = callback
      const envList = data.envList || []
      this.formData = {
        ...data
      }

      this.activeTab = defaultTab

      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        // 获取隐藏了的配置
        envList.forEach((item) => {
          const res = this.envConfigList.find(
            (config) => config.key === item.env
          )
          if (!res) {
            this.envConfigHiddenList.push(item)
          }
        })
        this.envConfigList.forEach((item, index) => {
          // 获取对应显示环境的配置项
          const config = (envList || []).find(
            (config) => config.env === item.key
          )
          const form = this.$refs[item.key + '_EnvForm'][0]
          form.setData(config)
        })
      })
    },

    close () {
      this.showVisible = false
      this.envConfigHiddenList = []
    },

    async submit () {
      try {
        await this.$refs.form.validate()
        const envResList = await Promise.all(
          this.envConfigList.map((item, index) => {
            const form = this.$refs[item.key + '_EnvForm'][0]
            return form.getData()
          })
        )
        const envList = []
        for (var i = 0; i < envResList.length; i++) {
          const res = envResList[i]
          if (res === false) {
            this.activeTab = this.envConfigList[i].key
            return
          }
          res.host && envList.push(res)
        }
        let params = {}
        let request = null

        const { id, key, name, type, remark } = this.formData
        if (this.isNew) {
          request = postHmdatasource
          params = { key, name, type, remark }
        } else {
          request = putHmdatasource
          params = { id, name, remark }
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === 'string' ? params[key].trim() : params[key]
        }

        params.envList = []
        params.envList = [...envList, ...this.envConfigHiddenList]
        request(params)
          .then((res) => {
            this.close()
            this.callback()
          })
          .finally(() => {})
      } catch (error) {
        console.log(error)
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
